<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/1
 * Time: 16:41
 */

namespace app\api\service;
use app\api\model\Order as OrderModel;
use app\lib\exception\BaseException;
use app\lib\exception\TokenException;
use think\Loader;

Loader::import('WxPay.WxPay',EXTEND_PATH,'.Api.php');

class PayService
{

    private $orderID;
    private $orderNO;

    public function __construct($orderID)
    {
        $this->orderID = $orderID;
    }


    public function pay(){
        $this->checkOrderValid();
        $orderService = new OrderService();
        $orderStatus = $orderService->checkOrderStock($this->orderID);
        if(!$orderStatus['pass']){
            return $orderStatus;
        }
        return $this->makeWxPreOrder($orderStatus['orderPrice']);
    }

    /**
     * @throws TokenException
     *  $wxOrderData->SetOut_trade_no($this->orderNo);
    $wxOrderData->SetTrade_type('JSAPI');
    $wxOrderData->SetTotal_fee($totalPrice * 100);
    $wxOrderData->SetBody('零食商贩');
    $wxOrderData->SetOpenid($openid);
    $wxOrderData->SetNotify_url(config('secure.pay_back_url'));
     */
    public function makeWxPreOrder($totalPrice){
        $openid = TokenService::getTokenVar('openid');
        if(!$openid){
            throw new TokenException();
        }
        $wxData = new \WxPayUnifiedOrder();
        $wxData->SetOut_trade_no($this->orderNO);
        $wxData->SetTrade_type('JSAPI');
        $wxData->SetBody('水果');
        $wxData->SetTotal_fee($totalPrice);
        $wxData->SetOpenid($openid);
        $wxData->SetNotify_url('');  //回调地址

        return $this->getPaySignature($wxData);
    }

    public function getPaySignature($wxData){
        $wxOrder = \WxPayApi::unifiedOrder($wxData);
        if($wxOrder['return_code'] != 'SUCCESS' || $wxOrder['result_code'] !='SUCCESS'){
            return;
        }
        $this->recordPreOrder($wxOrder);
        $single = $this->getSign($wxOrder);

        return $single;
    }

    private function recordPreOrder($wxOrder){
        // 必须是update，每次用户取消支付后再次对同一订单支付，prepay_id是不同的
        OrderModel::where('id', '=', $this->orderID)
            ->update(['prepay_id' => $wxOrder['prepay_id']]);
    }

    /**
     * @param $wxOrder
     * $jsApiPayData = new \WxPayJsApiPay();
    $jsApiPayData->SetAppid(config('wx.app_id'));
    $jsApiPayData->SetTimeStamp((string)time());
    $rand = md5(time() . mt_rand(0, 1000));
    $jsApiPayData->SetNonceStr($rand);
    $jsApiPayData->SetPackage('prepay_id=' . $wxOrder['prepay_id']);
    $jsApiPayData->SetSignType('md5');
    $sign = $jsApiPayData->MakeSign();
    $rawValues = $jsApiPayData->GetValues();
    $rawValues['paySign'] = $sign;
    unset($rawValues['appId']);
    return $rawValues;
     */
    private function getSign($wxOrder){
        $jsApi = new \WxPayJsApiPay();
        $jsApi->SetAppid(config('app_id'));
        $jsApi->SetTimeStamp((string)time());
        $rand = md5(time() . mt_rand(0, 1000));
        $jsApi->SetNonceStr($rand);
        $jsApi->SetPackage('prepay_id=' . $wxOrder['prepay_id']);
        $jsApi->SetSignType('md5');
        $sign = $jsApi->MakeSign();
        $rawValues = $jsApi->GetValues();
        $rawValues['paySign'] = $sign;
        unset($rawValues['appId']);
        return $rawValues;
    }

    public function checkOrderValid(){
        $order = OrderModel::where('id',$this->orderID)->find();

        if(!TokenService::isValidOperate($order->user_id)){
            throw new BaseException(['msg'=>'订单与用户id不匹配']);
        }
        if(!($order->status==1)){
            throw new BaseException(['msg'=>'订单已经支付过了']);
        }

        $this->orderNO=$order->order_no;
        return true;
    }

}